package fortunata;

import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.plugin.PluginException;

import java.io.File;
import java.util.Map;

/**
 * Base class of the plugins that construct a SemWebApp
 */
public class FortunataPlugin {
    //Multiplatform line separator
    public final static String nl = System.getProperty("line.separator");
    //Multiplatform wiki lines separator.
    public final static String wnl = "\\\\" + nl;
    //The extension of the physical file asociated to each wiki page.
    public final static String wikiFileExtension = ".txt";

    public static String MSG_TYPE_OK = "information";
    public static String MSG_TYPE_WARN = "warning";


    /**
     * Icon used to link to semantic data. Uses wiki syntax. E.g.: IconsPage/rdf_powered.png
     * This icon must be exist as an attacment in the wiki page called IconsPage.
     */
    public static final String ImageSemData = "IconsPage/rdf_powered.png";


    /**
     * Utility to hide JSPWiki implementation details
     * @param context
     * @param wikiText
     * @return the HTML code under the current skin
     */
    public static final String renderWikiText (WikiContext context, String wikiText) {
       return context.getEngine().textToHTML(context, wikiText);
    }

    /**
     * Utility to hide JSPWiki implementation details. Renders a given wiki text in a form message area.
     * @param context
     * @param wikiText
     * @param msgType can be FortunataPlugin.MSG_TYPE_OK or FortunataPlugin.MSG_TYPE_WARN
     * @return the HTML code under the current skin
     */
    public static final String renderWikiText (WikiContext context, String wikiText, String msgType ) {
        String finalWikiText = "%%" + msgType + " " + nl +
                          wikiText + nl +
                          "%%";
        return context.getEngine().textToHTML(context, finalWikiText);
    }

    /**
     * Returns the directory where wiki pages file live.
     * @param context
     * @return
     */
    public static String getWorkDir(WikiContext context){
     //Context.getEngine().getWikiProperties().getProperty(...
     return context.getEngine().getWorkDir() //Usually workDir is especified in jspwiki.properties okDir/cache. Reason: this file is used by Lucene as it is.
                     + File.separator + "..";  //This is error prone, specially if workDir is not specified in jspwiki.properties. In this case a Tomcat tmp dir is used.
   }
    
    /**
     * Get the physical name of a given wiki page
     * @param context
     * @param wikiPageName
     * @return
     */
    public static String WikiPageName2FullFileName(WikiContext context, String wikiPageName){
        return getWorkDir(context) + File.separator +
                                          wikiPageName + wikiFileExtension;
    }

     /**
     * Returs the URL (http://....) in which this web application lives
     * @param context
     * @return
     */
    public static String getURLBase(WikiContext context){
        return context.getEngine().getBaseURL() ;
    }

    /**
     * Returns the directory in which JSP files live
     * @param context
     * @return
     */
    public static String getURLDirectory(WikiContext context){
        //return context.getEngine().getBaseURL() TODO
        //context.getEngine().getWikiProperties().getProperty(...
        return context.getEngine().getRootPath();  //Warning: it finish the path with slash
        //return "C:\\Archivos de programa\\Apache Software Foundation\\Tomcat 5.5\\webapps\\JSPWiki2453";
    }

    /**
     * Used to manage the JSPWiki forms
     */
    public static class FormManager {
        /**
         * Utility to get values of Wiki Forms input fields. Specialy oriented to fields with default values
         * (input fileds or selectors). Applying this method to other fields such as radio or toggle returns null if
         * none value is checked. For these cases use  getToggleFieldValue(...)
         * In order to user another filed types, use getFieldNoEmplyValue(...) method
         * This method is intended to users with some knowledge about wiki sintax.
         * @param name The name of the field. If there is NO field with such name, an exception is thrown.
         * @param parameterMap
         * @return  The value, or "" if there is no value (as is the case for input fields not filled). Value returned is trimmed.
         * @throws com.ecyrd.jspwiki.plugin.PluginException with a WikiText message
         */
        public static String getFieldValue (String name, Map parameterMap) throws PluginException {
            String val = (String) parameterMap.get(name);
            if (val != null) {
              val = val.trim();
            }else {
                 throw new PluginException("field named __"+ name +
                                           "__ was expected. Check the wiki text, probably is typed wrong.");
            }
            return val;
        }

        /**
         * This utility extends the functionaly of getFieldValue(..) method.
         * If the field has no value (empty field), an exception is thrown.
         * This method is intended to final users.
         * @param name
         * @param parameterMap
         * @param identificativeText In case of empty field, the wiki text message will exchange the internal field name
         * with a more "end-user" name.
         * @return
         * @throws PluginException
         */
        public static String getFieldNoEmplyValue(String name, Map parameterMap, String identificativeText) throws PluginException{
           String res = getFieldValue(name, parameterMap);
            if (res.equals("")){
               throw new PluginException("The field __"+ identificativeText + "__ can not be empty.");
            }
            return res;
        }

        /**
         * This method is intended for radio and toggle fields. If one of such a fields is not "clicked", an empty string
         * is returned. If the returned string is null it is impossible to know if it is due to:
         *  (1) field name do not exists in the form,
         *  (2) radio/toggle not clicked.
         * We will assume case 2, that is, a returned null means a radio/toggle not clicked
         * @param name
         * @param parameterMap
         * @return
         */
        public static String getToggleFieldValue (String name, Map parameterMap){
            String val = (String) parameterMap.get(name);
            return (val != null)? val.trim() : "";
        }
    }
}
